<template>
  <div class="app-container">


    <div v-for="i in freightRule.costRange.length">
      <div v-if="i==1" style="margin-bottom: 20px">默认运费
        <el-input v-model="freightRule.costRange[0]" style="width:80px"/>
        元
      </div>
      <div v-else style="margin-bottom: 20px">满
        <el-input v-model="freightRule.limitRange[i-1]" style="width:80px"/>
        元（含）以上
        <el-input style="width:80px" v-model="freightRule.costRange[i-1]"/>
        元
        <el-button v-waves type="danger" @click="handleDelete(i-1)">
          删除
        </el-button>
      </div>
    </div>

    <el-button v-waves type="primary" @click="addRule">
      添加规则
    </el-button>
    <el-button v-waves type="primary" @click="saveRule">
      保存
    </el-button>
  </div>

</template>

<script>
  import {getFreightRule, save} from '@/api/freightRule'
  import waves from '@/directive/waves' // waves directive
  export default {
    name: 'Freight',
    components: {},
    directives: {waves},
    data() {
      return {
        freightRule:{
          id: null,
          costRange: [0],
          limitRange: [0],
        }
      }
    },

    created() {
      this.getSetting();
    },
    methods: {
      getSetting(){
        getFreightRule().then(r1=>{
          this.freightRule = r1.data
        })
      },
      addRule() {
        this.freightRule.costRange.push(0)
        this.freightRule.limitRange.push(0)
      },
      handleDelete(index) {
        this.freightRule.costRange.splice(index, 1)
        this.freightRule.limitRange.splice(index, 1)
      },
      saveRule() {
        let checkLength = true
        let checkSort = true

        //检查设置是否错误
        if (this.freightRule.costRange.length !== this.freightRule.limitRange.length) {
          checkLength = false
        }
        checkSort = this.checkCostRange(this.freightRule.costRange)
          && this.checkLimitRange(this.freightRule.limitRange)

        if(!checkSort || !checkLength){
          this.$message({
            message: '设置有误！请检查',
            type: 'warning'
          })
        }else{
          //保存
          save(this.freightRule).then(r1=>{
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      },

      checkCostRange(range) {
        for (var i = 1; i < range.length; i++) {
          if (parseInt(range[i]) >= parseInt(range[i - 1])) {
            return false;
          }
        }
        return true;
      },

      checkLimitRange(range) {
        for (var i = 1; i > range.length; i++) {
          if (parseInt(range[i]) <= parseInt(range[i - 1])) {
            return false;
          }
        }
        return true;
      },

    }
  }
</script>
